<?php

/**
 * Description of UserOptionController
 *
 * @author Poh Nean
 */
class UserOptionController extends PsController
{
	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'users' => array('@'),
					)), parent::accessRules());
	}

    public function filters()
    {
        return CMap::mergeArray(parent::filters(), array(
                    'ajaxOnly + save'
                ));
    }

    public function actionSave()
    {
        if ($_POST["name"]) {
            $response = array();

            $dropdown = Dropdown::model()->findByAttributes(array('name' => $_POST["name"]));

            if ($dropdown) {
                $transaction = Yii::app()->db->beginTransaction();

                try {
                    $allOptions = array();
                    if (!empty($_POST["options"])) {
                        // Remove options
                        $criteria = new CDbCriteria();
                        $criteria->addNotInCondition('value', $_POST["options"]);
                        $criteria->compare('dropdown_id', $dropdown->id);
                        $criteria->compare('user_id', Yii::app()->user->id);
                        $optionsToRemove = DropdownOption::model()->findAll($criteria);

                        if (!empty($optionsToRemove)) {
                            foreach ($optionsToRemove as $optionToRemove) {
                                $optionToRemove->delete();
                            }
                        }

                        // Add new options
                        $criteria = new CDbCriteria();
                        $criteria->addInCondition('value', $_POST["options"]);
                        $criteria->compare('dropdown_id', $dropdown->id);
                        $criteria->compare('user_id', Yii::app()->user->id);
                        $existingOptions = DropdownOption::model()->findAll($criteria);

                        foreach ($existingOptions as $existingOption) {
                            $allOptions[] = $existingOption->value;
                        }

                        foreach ($_POST["options"] as $i => $option) {
                            if (!in_array($option, $allOptions)) {
                                $dropdownOption = new DropdownOption;
                                $dropdownOption->user_id = Yii::app()->user->id;
                                $dropdownOption->value = trim($option);
                                $dropdownOption->pos = $i + 1;
                                $dropdownOption->dropdown_id = $dropdown->id;
                                $dropdownOption->save();
                                
                                $allOptions[] = $option;
                            }
                        }
                    }

                    $transaction->commit();

                    // save new options
                    $response['result'] = 'success';
                    $response['options'] = $allOptions;
                } catch (CDbException $e) {
                    $response['result'] = 'failure';
                    $transaction->rollback();
                }
            } else {
                $response['result'] = 'failure';
                $response['errorMsg'] = 'Object not found.';
            }

            print json_encode($response);
        }
    }

    public function getNextPos($dropdownId)
    {
        $sql = "SELECT MAX(pos) FROM `dropdown_option` WHERE dropdown_id = :dropdown_id";
        $pos = Yii::app()->db->createCommand($sql)->query(array(':dropdown_id' => $dropdownId)) + 1;

        return $pos;
    }

}

?>
